package com.hongru.ums.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.DynamicParameter;
import com.github.xiaoymin.knife4j.annotations.DynamicParameters;
import com.google.common.base.Joiner;
import com.hongru.cms.entity.CmsContent;
import com.hongru.cms.entity.CmsCourse;
import com.hongru.cms.entity.CmsCourseApply;
import com.hongru.cms.entity.CmsVideo;
import com.hongru.cms.entity.vo.CmsContentListVo;
import com.hongru.cms.entity.vo.CmsCourseVo;
import com.hongru.cms.entity.vo.CmsVideoVo;
import com.hongru.constant.DictConstant;
import com.hongru.ebean.EbeanUtil;
import com.hongru.ebean.HongRuPage;
import com.hongru.ebean.StatusDto;
import com.hongru.exception.JeecgOrmException;
import com.hongru.mms.entity.MmsSiteMessageMember;
import com.hongru.mms.entity.vo.MmsSiteMessageMemberVo;
import com.hongru.mms.websocket.WebSocket;
import com.hongru.system.entity.SysMessage;
import com.hongru.system.entity.SysCategory;
import com.hongru.system.util.PrintToPdfUtil;
import com.hongru.ums.entity.*;
import com.hongru.ums.entity.dto.UmsDynamicDto;
import com.hongru.ums.entity.dto.UmsPeUpload;
import com.hongru.ums.entity.vo.*;
import com.hongru.ums.service.UmsPeService;
import com.hongru.util.BeanUtil;
import com.hongru.util.DateUtils;
import com.hongru.vo.LoginUser;
import com.hongru.vo.Result;
import io.ebean.DB;
import io.ebean.ExpressionList;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description
 * @Copyright (c) 1998-2022 北京新鸿儒世纪网络技术有限公司 All Rights Reserved.
 * @Url https://www.xinhongru.com
 * @ClassName UmsApiController
 * @Author salter <salter@vip.163.com>
 * @Version V1.0.0
 * @Since 1.0
 * @Date 2022/4/1 10:39
 */
@RestController
@RequestMapping("/ums")
@Slf4j
@Api(tags = "UMS接口汇总")
public class UmsApiController {


    @Value(value = "${hongru.path.upload}")
    private String uploadpath;
    @Value(value = "${jo.domain}")
    private String domain;
    @Autowired
    private WebSocket webSocket;

    @Autowired
    private UmsPeService peService;

    @GetMapping("/findSiteMessage")
    @ApiOperation(value = "站内信查询", tags = "站内信管理")
    public Result<HongRuPage<MmsSiteMessageMemberVo>> findSiteMessage() {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        JSONObject searchObj = new JSONObject();
        searchObj.put("memberId", loginUser.getId());
        return Result.OK(EbeanUtil.pageList(searchObj, MmsSiteMessageMemberVo.class));
    }

    @GetMapping(value = "/readSiteMessage/{id}")
    @ApiOperation(value = "站内信已读", tags = "站内信管理")
    @ApiOperationSupport(params = @DynamicParameters(properties = {
            @DynamicParameter(name = "id", value = "", example = "1"),
    }))
    public Result<?> readSiteMessage(@PathVariable String id) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        MmsSiteMessageMember mmsSiteMessageMember = new MmsSiteMessageMember();
        mmsSiteMessageMember.setId(id);
        mmsSiteMessageMember.setStatus(DictConstant.READ_STATUS_1);
        mmsSiteMessageMember.update();
        int count = EbeanUtil.initExpressionList(MmsSiteMessageMember.class).eq("memberId", loginUser.getId()).eq("status", DictConstant.READ_STATUS_0).findCount();
        return Result.OK(count);
    }


    @GetMapping(value = "/readAllSiteMessage")
    @ApiOperation(value = "站内信全部已读", tags = "站内信管理")
    public Result<?> readAllSiteMessage() {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        int count = EbeanUtil.initExpressionList(MmsSiteMessageMember.class).eq("memberId", loginUser.getId()).eq("status", DictConstant.READ_STATUS_0).findCount();
        DB.sqlUpdate("update mms_site_message_member set status=1 where member_id='" + loginUser.getId() + "'").execute();
        return Result.OK(count);
    }


    @ApiOperation(value = "体重打卡", tags = "打卡管理")
    @GetMapping(value = "/addClockInWeight")
    @ApiOperationSupport(ignoreParameters = {"umsDynamic.id"}, order = 1)
    public Result<UmsClockInWeight> addClockInWeight(@RequestParam(name = "weight") Double weight) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String date = DateUtils.getDate("yyyy-MM-dd");
        UmsClockInWeight clockInWeight = EbeanUtil.initExpressionList(UmsClockInWeight.class).where()
                .eq("memberId", loginUser.getId())
                .eq("clockInDate", date)
                .findOne();
        if (clockInWeight != null) {
            clockInWeight.setWeight(weight);
            clockInWeight.update();
        } else {
            clockInWeight = new UmsClockInWeight();
            clockInWeight.setMemberId(loginUser.getId());
            clockInWeight.setWeight(weight);
            clockInWeight.setClockInDate(new Date());
            clockInWeight.save();
        }
        return Result.OK("添加成功");
    }

    @GetMapping("/findClockInWeight")
    @ApiOperation(value = "体重打卡历史记录", tags = "打卡管理")
    @ApiOperationSupport(params = @DynamicParameters(properties = {
    }))
    public Result<HongRuPage<UmsClockInWeightVo>> findClockInWeight() {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        JSONObject searchObj = new JSONObject();
        searchObj.put("memberId", loginUser.getId());
        searchObj.put("order", "desc");
        searchObj.put("column", "clockInDate");
        return Result.OK(EbeanUtil.pageList(searchObj, UmsClockInWeightVo.class));
    }

    @PostMapping("/clockInShare")
    @ApiOperation(value = "打卡分享", tags = "打卡管理")
    @ApiOperationSupport(params = @DynamicParameters(properties = {
            @DynamicParameter(name = "type", value = "模板类型(m1:体重模板 m2:运动模板 )", example = "m1"),
    }))
    public Result<UmsClockInTemplateVo> clockInWeightShare(@RequestBody JSONObject searchObj) {
        String type = searchObj.getString("type");
        UmsClockInTemplateVo umsClockInTemplateVo = DB.findDto(UmsClockInTemplateVo.class, "SELECT NAME,TITLE,CONTENT,COVER FROM UMS_CLOCK_IN_TEMPLATE where deleted = 0 and status = 1 and type = '" + type + "' ORDER BY RAND() LIMIT 1").findOne();
        if (null == umsClockInTemplateVo) {
            throw new JeecgOrmException("无模板");
        }
        if (StringUtils.equals(DictConstant.CLOCKIN_TEMPLATE_TYPE_M1, type)) {
            LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            ExpressionList<UmsClockInWeight> el = EbeanUtil.initExpressionList(UmsClockInWeight.class).where()
                    .eq("memberId", loginUser.getId());
            UmsClockInWeight defaultClockInWeight = new UmsClockInWeight().setWeight(0D);
            UmsClockInWeight oldObj = el.orderBy("clockInDate asc").setMaxRows(1).findOneOrEmpty().orElse(defaultClockInWeight);
            UmsClockInWeight newObj = el.orderBy("clockInDate desc").setMaxRows(1).findOneOrEmpty().orElse(defaultClockInWeight);
            umsClockInTemplateVo.setOldWeight(oldObj.getWeight());
            umsClockInTemplateVo.setNewWeight(newObj.getWeight());
        }
        return Result.OK(umsClockInTemplateVo);
    }

    @GetMapping(value = "/findClockInWeightTable")
    @ApiOperation(value = "体重打卡 年/月/周 统计", tags = "打卡管理")
    @ApiOperationSupport(ignoreParameters = {"umsDynamic.id"}, order = 1)
    public Result<List<UmsClockInWeightVo>> findClockInWeightTable(String type) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        int dayNums = 7;
        if (StringUtils.equals(DictConstant.PERIOD_YEAR, type)) {
            dayNums = 365;
        }
        if (StringUtils.equals(DictConstant.PERIOD_MONTH, type)) {
            dayNums = 30;
        }
        List<UmsClockInWeightVo> list = EbeanUtil.initExpressionList(UmsClockInWeightVo.class).where()
                .eq("memberId", loginUser.getId())
                .ge("clockInDate", getBeforeWorkDays(new Date(), dayNums))
                .orderBy("clockInDate asc")
                .findList();
        System.out.println(getBeforeWorkDays(new Date(), dayNums));
        return Result.OK(list);
    }

    private static String getBeforeWorkDays(Date endDate, int workDays) {
        Calendar c1 = Calendar.getInstance();
        c1.setTime(endDate);
        c1.set(Calendar.DATE, c1.get(Calendar.DATE) - (workDays - 1));
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        return df.format(c1.getTime());
    }

    @ApiOperation(value = "发布动态及饮食打卡", tags = "健康圈管理")
    @ApiOperationSupport(ignoreParameters = {"umsDynamic.id"}, order = 1)
    @PostMapping(value = "/addDynamic")
    public Result<UmsDynamic> add(@RequestBody @Valid UmsDynamicDto umsDynamicDto) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        UmsDynamic umsDynamic = BeanUtil.copy(umsDynamicDto, UmsDynamic.class);
        umsDynamic.setMemberId(loginUser.getId());
        if (DictConstant.TOPIC_1.equals(umsDynamic.getTopic())) {
            umsDynamic.setIsShow(DictConstant.IS_OPEN_1);
        }
        umsDynamic.save();
        return Result.OK("添加成功");
    }

    @ApiOperation(value = "发布健康问题", tags = "健康圈管理")
    @ApiOperationSupport(ignoreParameters = {"umsQa.id"}, order = 2)
    @PostMapping(value = "/addQa")
    public Result<UmsQa> addQa(@RequestBody UmsQa umsQa) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        umsQa.setMemberId(loginUser.getId());
        umsQa.save();
        return Result.OK("发布成功");
    }

    @PostMapping("/findQaPageList")
    @ApiOperation(value = "健康问答列表", tags = "健康圈管理")
    @ApiOperationSupport(params = @DynamicParameters(properties = {
            @DynamicParameter(name = "memberId", value = "会员ID(不传就是所有健康问答)", example = ""),
    }))
    public Result<HongRuPage<UmsQaVo>> findQaPageList(@RequestBody JSONObject searchObj) {
        return Result.OK(EbeanUtil.pageList(searchObj, UmsQaVo.class));
    }

    @GetMapping("/getQa/{id}")
    @ApiOperation(value = "健康问答详情", tags = "健康圈管理")
    public Result<UmsQaVo> queryQaById(@PathVariable String id) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        UmsQaVo qa = EbeanUtil.initExpressionList(UmsQaVo.class).idEq(id).findOne();
        int likeCount = DB.find(UmsLikeRecord.class).where().
                in("sourceId", id).
                eq("memberId", loginUser.getId()).
                eq("operation", "like").findCount();
        if (likeCount > 0) {
            qa.setIsGiveLike(true);
        }
        qa.setPv(qa.getPv() + 1);
        qa.update();
        return Result.OK(qa);
    }


    @ApiOperation(value = "发布评论", tags = "健康圈管理")
    @ApiOperationSupport(ignoreParameters = {"UmsCommentVo.id"}, order = 2)
    @PostMapping(value = "/addComment")
    public Result<UmsCommentVo> add(@RequestBody UmsComment umsComment) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        umsComment.setMemberId(loginUser.getId());
        UmsCommentVo commentVo = EbeanUtil.initExpressionList(UmsCommentVo.class).idEq(umsComment.getSourceId()).findOne();
        if (!umsComment.getType().equals(DictConstant.COMMENT_TYPE_UMSCOMMENT)) {
            umsComment.setTheme(umsComment.getType());
        } else {
            umsComment.setTheme(commentVo.getTheme());
            if (DictConstant.MEMBER_TYPE_1.equals(commentVo.getMember().getMemberType()) && !DictConstant.COMMENT_TYPE_CMSCONTENT.equals(umsComment.getTheme())) {
                SysMessage sysMessage = new SysMessage();
                sysMessage.setTitle("您有一条评论待回复");
                sysMessage.setContent(umsComment.getContent());
                sysMessage.setBusId(commentVo.getSourceId());
                sysMessage.save();
                JSONObject searchObj = new JSONObject();
                searchObj.put("status", DictConstant.READ_STATUS_0);
                HongRuPage<SysMessage> sysMessageHongRuPage = EbeanUtil.pageList(searchObj, SysMessage.class);
                webSocket.sendMessage(JSONObject.toJSONStringWithDateFormat(sysMessageHongRuPage, "yyyy-MM-dd HH:mm:ss"));
            }
        }
        umsComment.save();
        EbeanUtil.changeColumnNum(umsComment.getType(), "comment_num", umsComment.getSourceId(), "+1");
        return Result.OK("添加成功");
    }

    @PostMapping(value = "/likeAndCollect")
    @ApiOperation(value = "点赞收藏接口(取消也调用此接口，参数不变)", tags = "健康圈管理")
    @ApiOperationSupport(order = 3)
    public Result likeAndCollect(@RequestBody UmsLikeRecord likeRecord) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        likeRecord.setMemberId(loginUser.getId());
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(likeRecord);
        try {
            String columnName = likeRecord.getOperation() + "_num";
            int delCount = EbeanUtil.initExpressionList(jsonObject, UmsLikeRecord.class).delete();
            if (delCount > 0) {
                EbeanUtil.changeColumnNum(likeRecord.getType(), columnName, likeRecord.getSourceId(), "-1");
                return Result.OK();
            }
            EbeanUtil.changeColumnNum(likeRecord.getType(), columnName, likeRecord.getSourceId(), "+1");
        } catch (Exception ignored) {

        }
        likeRecord.save();
        return Result.OK();
    }

    @PostMapping("/queryDynamicPageList")
    @ApiOperation(value = "动态及饮食打卡列表", tags = "健康圈管理")
    @ApiOperationSupport(params = @DynamicParameters(properties = {
            @DynamicParameter(name = "memberId", value = "会员ID(不传就是所有动态)", example = ""),
            @DynamicParameter(name = "topic", value = "话题(1:日常动态(动态列表不用传) 2:饮食打卡 )", example = "1"),
    }))
    public Result<HongRuPage<UmsDynamicVo>> queryDynamicPageList(@RequestBody JSONObject searchObj) {
        searchObj.put("status", 1);
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (null == searchObj.getInteger("topic")) {
            searchObj.put("isShow", 1);
        }
        HongRuPage<UmsDynamicVo> umsDynamicVoHongRuPage = EbeanUtil.pageList(searchObj, UmsDynamicVo.class);
        List<UmsDynamicVo> records = umsDynamicVoHongRuPage.getRecords();
        List<String> shareIds = records.stream().map(e -> e.getId()).collect(Collectors.toList());
        List<UmsLikeRecord> giveLikes = DB.find(UmsLikeRecord.class).where().
                in("sourceId", shareIds).
                eq("memberId", loginUser.getId()).
                eq("operation", "like").findList();
        for (UmsDynamicVo comment : records) {
            comment.setIsGiveLike(giveLikes.stream().anyMatch(e -> comment.getId().equals(e.getSourceId())));
        }
        umsDynamicVoHongRuPage.setRecords(records);
        return Result.OK(umsDynamicVoHongRuPage);
    }


    @GetMapping("/queryDynamicById/{id}")
    @ApiOperation(value = "动态详情", tags = "健康圈管理")
    public Result<UmsDynamicVo> queryDynamicById(@PathVariable String id) {
        UmsDynamicVo dynamicVo = EbeanUtil.initExpressionList(UmsDynamicVo.class).idEq(id).findOne();
        return Result.OK(dynamicVo);
    }

    @PostMapping("/queryCommentPageList")
    @ApiOperation(value = "评论列表", tags = "健康圈管理")
    @ApiOperationSupport(params = @DynamicParameters(properties = {
            @DynamicParameter(name = "sourceId", value = "评论数据ID", example = ""),
    }))
    public Result<HongRuPage<UmsCommentVo>> queryCommentPageList(@RequestBody JSONObject searchObj) {
        searchObj.put("status", 1);
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        HongRuPage<UmsCommentVo> UmsCommentVoHongRuPage = EbeanUtil.pageList(searchObj, UmsCommentVo.class);
        List<UmsCommentVo> records = UmsCommentVoHongRuPage.getRecords();
        List<String> shareIds = records.stream().map(e -> e.getId()).collect(Collectors.toList());
        List<UmsLikeRecord> giveLikes = DB.find(UmsLikeRecord.class).where().
                in("sourceId", shareIds).
                eq("memberId", loginUser.getId()).
                eq("operation", "like").findList();
        for (UmsCommentVo comment : records) {
            comment.setIsGiveLike(giveLikes.stream().anyMatch(e -> comment.getId().equals(e.getSourceId())));
        }
        UmsCommentVoHongRuPage.setRecords(records);
        return Result.OK(UmsCommentVoHongRuPage);
    }


    @PostMapping("/queryCoursePageList")
    @ApiOperation(value = "健康课堂列表", tags = "健康课堂管理")
    @ApiOperationSupport(params = @DynamicParameters(properties = {
            @DynamicParameter(name = "isHot", value = "是否热门(0:否 1:是 )", example = "0"),
    }))
    public Result<HongRuPage<CmsCourseVo>> queryCoursePageList(@RequestBody JSONObject searchObj) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        searchObj.put("status", 1);
        HongRuPage<CmsCourseVo> cmsCourseVoHongRuPage = EbeanUtil.pageList(searchObj, CmsCourseVo.class);
        List<CmsCourseApply> courseApplies = EbeanUtil.initExpressionList(CmsCourseApply.class).where().eq("memberId", loginUser.getId()).findList();
        List<CmsCourseVo> records = cmsCourseVoHongRuPage.getRecords();
        for (CmsCourseVo record : records) {
            record.setIsApply(courseApplies.stream().anyMatch(e -> e.getCourseId().equals(record.getId())));
        }
        cmsCourseVoHongRuPage.setRecords(records);
        return Result.OK(cmsCourseVoHongRuPage);
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "健康课堂详情", tags = "健康课堂管理")
    public Result<CmsCourseVo> queryCourseById(@PathVariable String id) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        CmsCourseVo course = EbeanUtil.initExpressionList(CmsCourseVo.class).idEq(id).findOne();
        int count = EbeanUtil.initExpressionList(CmsCourseApply.class).where().eq("memberId", loginUser.getId()).eq("courseId", id).findCount();
        if (count > 0 && !course.getApplyStatus().equals("已结束")) {
            course.setIsApply(true);
        }
        String detail = course.getDetail().replaceAll("jeecg-orm", domain);
        course.setDetail(detail);
        return Result.OK(course);
    }


    @ApiOperation(value = "健康课堂报名", tags = "健康课堂管理")
    @ApiOperationSupport(ignoreParameters = {"cmsCourseApply.id"}, order = 4)
    @PostMapping(value = "/addCourseApply")
    public Result addCourseApply(@RequestBody @Valid CmsCourseApply cmsCourseApply) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        cmsCourseApply.setMemberId(loginUser.getId());
        CmsCourseVo course = EbeanUtil.initExpressionList(CmsCourseVo.class).idEq(cmsCourseApply.getCourseId()).findOne();
        if (!"报名中".equals(course.getApplyStatus())) {
            return Result.error("课程暂不可报名");
        }
        if (course.getCourseNum().equals(course.getApplyNum())) {
            return Result.error("课程已报满");
        }
        int count = EbeanUtil.initExpressionList(CmsCourseApply.class).where().
                eq("courseId", cmsCourseApply.getCourseId()).
                eq("memberId", cmsCourseApply.getMemberId()).findCount();
        if (count > 0) {
            return Result.error("已经报名过此活动");
        }
        cmsCourseApply.save();
        course.setApplyNum(course.getApplyNum() + 1);
        course.update();
        return Result.OK("报名成功");
    }

    @PostMapping("/queryCourseByMember")
    @ApiOperation(value = "我的报名列表", tags = "健康课堂管理")
    @ApiOperationSupport(params = @DynamicParameters(properties = {
    }))
    public Result<HongRuPage<CmsCourseVo>> queryCourseByMember(@RequestBody JSONObject searchObj) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        searchObj.put("memberId", loginUser.getId());
        HongRuPage<CmsCourseApply> courseApplyHongRuPage = EbeanUtil.pageList(searchObj, CmsCourseApply.class);
        List<CmsCourseApply> records = courseApplyHongRuPage.getRecords();
        List<String> courseIds = records.stream().map(CmsCourseApply::getCourseId).collect(Collectors.toList());
        List<CmsCourseVo> list = EbeanUtil.initExpressionList(CmsCourseVo.class).idIn(courseIds).findList();
        HongRuPage<CmsCourseVo> cmsCourseHongRuPage = new HongRuPage<>(courseApplyHongRuPage.getPageNo(), courseApplyHongRuPage.getPageSize());
        cmsCourseHongRuPage.setRecords(list);
        return Result.OK(cmsCourseHongRuPage);
    }


    @ApiOperation(value = "运动打卡接口", tags = "打卡管理")
    @ApiOperationSupport(order = 5)
    @GetMapping(value = "/sportsClock")
    public Result sportsClock(String planId, String videoId) {
        int count = EbeanUtil.initExpressionList(UmsExercisePlanDetail.class).idEq(planId).contains("clockVideoIds", videoId).findCount();
        if (count > 0) {
            return Result.OK("打卡成功");
        }
        ExpressionList<UmsExercisePlanDetail> el = EbeanUtil.initExpressionList(UmsExercisePlanDetail.class).idEq(planId);
        el.asUpdate().setRaw("clock_video_ids=CONCAT(ifnull(clock_video_ids,''),'," + videoId + "')").update();
        UmsExercisePlanDetail exercisePlanDetail = EbeanUtil.initExpressionList(UmsExercisePlanDetail.class).idEq(planId).findOne();
        String[] idsArr = exercisePlanDetail.getVideoIds().split(",");
        if (idsArr.length == exercisePlanDetail.getVideoIds().split(",").length) {
            exercisePlanDetail.setStatus(DictConstant.YN_1);
            exercisePlanDetail.update();
        }
        return Result.OK("打卡成功");
    }

    @GetMapping("/queryExercisePlanDateList")
    @ApiOperation(value = "运动计划日期列表", tags = "运动计划管理")
    @ApiOperationSupport(params = @DynamicParameters(properties = {
    }))
    public Result<HongRuPage<UmsExercisePlanDetailVo>> queryExercisePlanDateList() {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        JSONObject searchObj = new JSONObject();
        searchObj.put("column", "planDate");
        searchObj.put("order", "asc");
        searchObj.put("exercisePlan_status", 1);
        searchObj.put("exercisePlan_memberId", loginUser.getId());
        return Result.OK(EbeanUtil.pageList(searchObj, UmsExercisePlanDetailVo.class));
    }


    @GetMapping("/queryExercisePlanVideoList")
    @ApiOperation(value = "运动计划视频列表", tags = "运动计划管理")
    @ApiOperationSupport(params = @DynamicParameters(properties = {
            @DynamicParameter(name = "planId", value = "计划id", example = "c316aa06a8a74581aa488681ef80e6ef"),
    }))
    public Result<HongRuPage<CmsVideoVo>> queryExercisePlanVideoList(String planId) {
        UmsExercisePlanDetail exercisePlanDetail = EbeanUtil.initExpressionList(UmsExercisePlanDetail.class).idEq(planId).findOne();
        String videoIds = exercisePlanDetail.getVideoIds();
        String clockVideoIds = exercisePlanDetail.getClockVideoIds();
        String[] idArr = videoIds.split(",");
        List<CmsVideoVo> list = EbeanUtil.initExpressionList(CmsVideoVo.class).idIn(idArr).findList();
        for (CmsVideoVo cmsVideoVo : list) {
            cmsVideoVo.setIsClock(clockVideoIds.contains(cmsVideoVo.getId()));
        }
        HongRuPage<CmsVideoVo> hongRuPage = new HongRuPage();
        hongRuPage.setRecords(list);
        return Result.OK(hongRuPage);
    }

    @GetMapping("/getVideo/{id}")
    @ApiOperation(value = "运动视频详情", tags = "运动计划管理")
    public Result<CmsVideo> queryVideoById(@PathVariable String id) {
        CmsVideo Video = EbeanUtil.initExpressionList(CmsVideo.class).idEq(id).findOne();
        return Result.OK(Video);
    }


    @PostMapping("/queryMrPageList")
    @ApiOperation(value = "医学报告列表", tags = "报告管理")
    @ApiOperationSupport(params = @DynamicParameters(properties = {
            @DynamicParameter(name = "categoryCode", value = "报告类型", example = "F112"),
            @DynamicParameter(name = "type", value = "报告版本(1:基础版 2:定制版 )", example = "1"),
            @DynamicParameter(name = "reportDate", value = "报告日期", example = "2022-04-07"),
    }))
    public Result<HongRuPage<UmsMr>> queryMrPageList(@RequestBody JSONObject searchObj) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        searchObj.put("memberId", loginUser.getId());
        searchObj.put("status", 1);
        searchObj.put("column", "reportDate");
        searchObj.put("order", "desc");
        return Result.OK(EbeanUtil.pageList(searchObj, UmsMr.class));
    }

    @PostMapping("/queryMrContentPageList")
    @ApiOperation(value = "报告内容列表", tags = "报告管理")
    @ApiOperationSupport(params = @DynamicParameters(properties = {
            @DynamicParameter(name = "mrId", value = "报告ID", example = "2fe7dd1f7fe64f38ac5bbfd276180201"),
    }))
    public Result<HongRuPage<UmsMrContent>> queryMrContentPageList(@RequestBody JSONObject searchObj) {
        return Result.OK(EbeanUtil.pageList(searchObj, UmsMrContent.class));
    }

    @PostMapping("/queryPePageList")
    @ApiOperation(value = "身体检测报告列表", tags = "报告管理")
    @ApiOperationSupport(params = @DynamicParameters(properties = {
            @DynamicParameter(name = "categoryCode", value = "检测项目", example = "F110"),
    }))
    public Result queryPePageList(@RequestBody JSONObject searchObj) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        searchObj.put("status", DictConstant.STATUS_1);
        searchObj.put("memberId", loginUser.getId());
        String categoryCode = searchObj.getString("categoryCode");
        SysCategory pCategory = EbeanUtil.initExpressionList(SysCategory.class).eq("code", categoryCode).findOne();
        Map<String, SysCategory> codeCategoryMap = new HashMap<>();
        codeCategoryMap.put(pCategory.getCode(), pCategory);
        if (pCategory.getHasChild()) {
            List<SysCategory> categoryList = EbeanUtil.initExpressionList(SysCategory.class).eq("pid", pCategory.getId()).findList();
            List<String> idList = categoryList.stream().map(SysCategory::getCode).collect(Collectors.toList());
            String ids = Joiner.on(",").join(idList);
            searchObj.put("categoryCode", ids);
            codeCategoryMap.putAll(categoryList.stream().collect(Collectors.toMap(SysCategory::getCode, e -> e)));
        }
        HongRuPage<UmsPe> umsPeHongRuPage = EbeanUtil.pageList(searchObj, UmsPe.class);
        List<UmsPe> records = umsPeHongRuPage.getRecords();
        Map<String, List<UmsPe>> peGroupMap = records.stream().collect(Collectors.groupingBy(UmsPe::getCategoryCode));
        Map<String, List<UmsPe>> peGroupByCategory = new HashMap<>();
        for (Map.Entry<String, List<UmsPe>> entry : peGroupMap.entrySet()) {
            SysCategory category = codeCategoryMap.get(entry.getKey());
            peGroupByCategory.put(category.getName(), entry.getValue());
        }
        return Result.OK(peGroupByCategory);
    }

    @ApiOperation(value = "身体检测报告上传", tags = "报告管理")
    @PostMapping(value = "peUpload")
    public Result peUpload(@RequestBody UmsPeUpload umsPeUpload) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        UmsPe umsPe = BeanUtil.copy(umsPeUpload, UmsPe.class);
        umsPe.setMemberId(loginUser.getId());
        String[] imagePathList = umsPe.getImage().split(",");
        String pdfName = "/temp/" + umsPe.getName() + "_" + System.currentTimeMillis() + ".pdf";
        String pdfPath = uploadpath + pdfName;
        PrintToPdfUtil.toPdf(imagePathList, pdfPath);
        umsPe.setFile(pdfName);
        umsPe.save();
        peService.pdfToImage(umsPe);
        return Result.OK("上传成功");
    }


    @GetMapping("/queryCollectList")
    @ApiOperation(value = "我的收藏", tags = "会员中心管理")
    @ApiOperationSupport(params = @DynamicParameters(properties = {
            @DynamicParameter(name = "categoryCode", value = "分类Code", example = "F12"),
    }))
    public Result<HongRuPage<CmsContentListVo>> queryCollectList(String categoryCode, String title) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        JSONObject searchObj = new JSONObject();
        searchObj.put("memberId", loginUser.getId());
        searchObj.put("type", "CmsContent");
        searchObj.put("operation", "collect");
        searchObj.put("content_categoryCode", categoryCode);
        searchObj.put("content_title", title);
        HongRuPage<UmsLikeRecordVo> umsLikeRecordHongRuPage = EbeanUtil.pageList(searchObj, UmsLikeRecordVo.class);
        List<UmsLikeRecordVo> records = umsLikeRecordHongRuPage.getRecords();
        List<CmsContentListVo> cmsContentLis = new ArrayList<>();
        List<SysCategory> list = EbeanUtil.initExpressionList(SysCategory.class).isNotNull("icon").findList();
        Map<String, String> collect = list.stream().collect(Collectors.toMap(SysCategory::getCode, SysCategory::getIcon));
        for (UmsLikeRecordVo umsLikeRecordVo : records) {
            CmsContent content = umsLikeRecordVo.getContent();
            CmsContentListVo contentListVo = BeanUtil.copy(content, CmsContentListVo.class);
            contentListVo.setCategoryIcon(collect.get(contentListVo.getCategoryCode()));
            contentListVo.setIsCollect(true);
            cmsContentLis.add(contentListVo);
        }
        HongRuPage<CmsContentListVo> hongRuPage = new HongRuPage();
        hongRuPage.setRecords(cmsContentLis);
        return Result.OK(hongRuPage);
    }

    @ApiOperation(value = "个人资料编辑", tags = "会员中心管理")
    @PostMapping(value = "/editMember")
    public Result<UmsMember> editMember(@RequestBody @Valid UmsMember umsMember) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        umsMember.setId(loginUser.getId());
        umsMember.update();
        return Result.OK("编辑成功");
    }

    @ApiOperation(value = "获取会员信息", tags = "会员中心管理")
    @GetMapping(value = "/queryMemberInfo")
    public Result<UmsMemberVo> queryMemberInfo() {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        UmsMemberVo memberVo = EbeanUtil.initExpressionList(UmsMemberVo.class).idEq(loginUser.getId()).findOne();
        int count = EbeanUtil.initExpressionList(MmsSiteMessageMember.class).eq("memberId", memberVo.getId()).eq("status", DictConstant.READ_STATUS_0).findCount();
        int collectCount = EbeanUtil.initExpressionList(UmsLikeRecord.class).eq("memberId", memberVo.getId()).eq("operation", DictConstant.LIKE_OPERATION_COLLECT).findCount();
        memberVo.setCollectCount(collectCount);
        memberVo.setMsgCount(count);
        return Result.OK(memberVo);
    }


}
